<script>
export default {
  name: "MyItem",
  props: {
    todoObj: Object
  },
  methods: {
    //选中当前的任务
    checkTodo(id){
      this.$bus.$emit("checkTodo", id)
    },
    //删除当前任务
    deleteTodo(id){
      this.$bus.$emit("deleteTodo",id)
    },
    editTodo(todoObj){
      // 判断当前todoObj对象是否包含isEdit属性,可以证明Vue框架中$Set方法会自动添加isEdit属性并且存在属性后再次$set会修改当前属性的属性值
      console.log("是否有isEdit属性:", Object.prototype.hasOwnProperty.call(todoObj, "isEdit"));
      this.$set(todoObj, "isEdit", true);
      console.log("更新后是否有isEdit属性:", Object.prototype.hasOwnProperty.call(todoObj, "isEdit"));
      // 在下次 DOM 更新后聚焦到输入框
      this.$nextTick(() => {
        this.$refs.editInput && this.$refs.editInput.focus();
      });
    },
    handleBlur(todoObj){
      const newContent = event.target.value.trim();
      if(newContent === ""){
        alert("待办内容不能为空");
        event.target.value = todoObj.content;
      } else if(newContent !== todoObj.content) {
        todoObj.content = newContent;
        this.$bus.$emit("updateTodo", todoObj)
      }
      todoObj.isEdit = false;
    }
  },
  beforeDestroy() {
    // 只移除当前组件实例的监听器，而不是所有同名监听器
    this.$bus.$off("checkTodo", this.checkTodo);
    this.$bus.$off("deleteTodo", this.deleteTodo);
    this.$bus.$off("updateTodo", this.updateTodo);
  }
}
</script>

<template>
  <li>
    <label>
      <input type="checkbox" :checked="todoObj.done" @click="checkTodo(todoObj.id)"/>
      <span v-show="!todoObj.isEdit">{{ todoObj.content }}</span>
      <input v-show="todoObj.isEdit"
             type="text"
             ref="editInput"
             :value="todoObj.content"
             @blur="handleBlur(todoObj, $event)"
             @keyup.enter="handleBlur(todoObj, $event)"/>
    </label>
    <button class="btn btn-danger" @click="deleteTodo(todoObj.id)" v-show="!todoObj.isEdit">删除</button>
    <button class="btn btn-edit" @click="editTodo(todoObj)" v-show="!todoObj.isEdit">编辑</button>
  </li>
</template>

<style scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover {
  background: #aaa;
}

li:hover button{
  display: block;
}
</style>